package com.fightingFish.user.dao.impl;

import com.fightingFish.user.bean.Gift;
import com.fightingFish.user.bean.Record;
import com.fightingFish.user.bean.State;
import com.fightingFish.user.bean.User;
import com.fightingFish.user.dao.UserDao;
import com.fightingFish.util.DateUtil;
import com.fightingFish.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;

public class UserDaoImpl implements UserDao {

    /**
     * 方法描述：查询手机号是否存在
     *
     * @param phone 查询的电话号码
     * @return true：存在
     * false：不存在
     */
    @Override
    public boolean queryPhoneFromUser(String phone) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //定义sql语句
        String sql = "select phone from user where phone = ?";
        try {
            //创建连接
            con = JdbcUtil.getConnection();
            //获取预编译对象
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            //执行sql语句
            rs = ps.executeQuery();
            if (rs.next()) {
                //表示数据库中存在该电话号码
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return false;
    }

    /**
     * 方法描述：从temp表中查询电话号码是否存在
     *
     * @param phone 查询的电话号码
     * @return true ：存在
     * false ：不存在
     */
    @Override
    public boolean queryPhoneFromTemp(String phone) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        // /定义sql语句
        String sql = "select phone from temp where phone = ?";
        try {
            //创建连接
            con = JdbcUtil.getConnection();
            //获取预编译对象
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            //执行sql语句
            rs = ps.executeQuery();
            if (rs.next()) {
                //表示数据库中存在该电话号码
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return false;
    }

    /**
     * 方法描述：修改临时验证码表中的验证码信息
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public boolean insertVeriCode(String mark, String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //定义sql语句
        String sql = "";
        int rows = 0;
        try {
            //创建连接
            con = JdbcUtil.getConnection();
            //判断标记
            if ("register".equals(mark)) {
                //注册
                sql = "insert into temp(phone,tempCode) values(?,?)";
                //获取预编译对象
                ps = con.prepareStatement(sql);
                //给占位符赋值
                ps.setString(1, phone);
                ps.setString(2, veriCode);
                //执行sql语句
                rows = ps.executeUpdate();
            } else if ("login".equals(mark)) {
                //登陆
                sql = "insert into user(veriCode) values(?) where phone = ?";
                //获取预编译对象
                ps = con.prepareStatement(sql);
                //给占位符赋值
                ps.setString(1, veriCode);
                ps.setString(2, phone);
                //执行sql语句
                rows = ps.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return rows > 0;
    }

    /**
     * 修改temp表中的验证码
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public boolean updateTempVeriCode(String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        int rows = 0;
        //定义sql语句
        String sql = "update temp set veriCode = ?,tempTimeOut = date_add(now(),interval 10 minute) where phone = ?";
        con = JdbcUtil.getConnection();
        try {
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, veriCode);
            ps.setString(2, phone);
            //执行sql语句
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
        return rows > 0;
    }

    /**
     * 向temp表中添加手机号以及验证码信息
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public boolean insertTempVeriCode(String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        int rows = 0;
        //定义sql语句
        String sql = "insert into temp values(?,?,date_add(now(),interval 10 minute))";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            ps.setString(2, veriCode);
            //执行sql语句
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
        return rows > 0;
    }

    /**
     * 修改user表中的验证码信息
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public boolean updateUserVeriCode(String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        int rows = 0;
        //定义sql语句
        String sql = "UPDATE user set veriCode = ?,deadline = date_add(now(),interval 10 minute) where phone = ?";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, veriCode);
            ps.setString(2, phone);
            //执行sql语句
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
        return rows > 0;
    }

    /**
     * 用户手机号注册
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public boolean phoneRegister(String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int rows = 0;
        //定义sql语句
        String sql = "SELECT * from temp where tempCode = ? and phone = ?";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, veriCode);
            ps.setString(2, phone);
            //执行sql语句
            rs = ps.executeQuery();
            if (rs.next()) {
                //获取验证码过期时间
                String date = rs.getString("tempTimeOut");
                Date tempTimeOut = DateUtil.string2Date(date, "yyyyMMddHHssSSS");
                if (tempTimeOut.getTime() > new Date().getTime()) {
                    //验证码未过期
                    //将该用户电话号码注册到user表中
                    register(phone);
                    //将temp表中的手机号以及验证码删除
                    deleteVeriCodeFromTemp(phone);
                    return true;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
        return false;
    }

    /**
     * 删除temp表中的手机号以及验证码信息
     *
     * @param phone
     */
    private void deleteVeriCodeFromTemp(String phone) {
        Connection con = null;
        PreparedStatement ps = null;
        //定义sql语句
        String sql = "DELETE from temp where phone = ?";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            //执行sql语句
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }

    }

    /**
     * 注册手机号
     *
     * @param phone
     */
    private void register(String phone) {
        Connection con = null;
        PreparedStatement ps = null;
        //定义sql语句
        String sql = "INSERT into user(phone) VALUES(?)";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            //执行sql语句
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
    }


    /**
     * 手机号登陆
     *
     * @param phone
     * @param veriCode
     * @return
     */
    @Override
    public User phoneLogin(String phone, String veriCode) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        //定义sql语句
        try {
            String sql = "SELECT * from user where phone = ? and veriCode = ?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            ps.setString(2, veriCode);
            //执行sql语句
            rs = ps.executeQuery();
            if (rs.next()) {
                //获取验证码过期时间
                String date = rs.getString("deadline");
                Date deadline = DateUtil.string2Date(date, "yyyyMMddHHssSSS");
                System.out.println("daophoneLogin");
                if (deadline.getTime() < new Date().getTime()) {
                    //验证码未过期
                    System.out.println("验证码是否过期");
                    user = new User();
                    user.setPhotoImgUrl(rs.getString("photoImgUrl"));
                    user.setUserId(rs.getInt("userId"));
                    user.setPhone(rs.getString("phone"));
                    user.setNickName(rs.getString("nickName"));
                    user.setAnchorOrUser(rs.getInt("anchorOrUser"));
                    deleteVeriCodeFromUser(phone);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return user;
    }

    /**
     * 通过用户ID查询用户个人信息
     *
     * @param userId
     * @return
     */
    @Override
    public User selectInfoByid(Integer userId) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //定义sql语句
            String sql = "select * from user u join state s on u.state=s.stateId where u.userId = ?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setInt(1, userId);
            //执行sql语句
            rs = ps.executeQuery();
            if (rs.next()) {
                User u = new User();
                u.setAnchorOrUser(rs.getInt("anchorOrUser"));
                u.setBalance(rs.getDouble("balance"));
                String date = rs.getString("createTime");
                u.setCreateTime(DateUtil.string2Date(date,"yyyyMMddHHssSSS"));
                u.setEmail(rs.getString("email"));
                u.setNickName(rs.getString("nickName"));
                u.setPhone(rs.getString("phone"));
                u.setPhotoImgUrl(rs.getString("photoImgUrl"));
                u.setSex(rs.getString("sex"));
                u.setUserLevel(rs.getInt("userlevel"));
                u.setSignDay(rs.getInt("signDay"));
                u.setSignInfo(rs.getString("signInfo"));

                State state = new State(rs.getString("stateName"));
                u.setState(state);

                u.setUserId(rs.getInt("userId"));
                return u;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, rs);
        }
        return null;
    }

    /**
     * *  用户可以根据id查找到当前用户
     *    修改个人的基本信息
     * * （密码，头像，昵称，性别，个性签名，手机号，邮箱）
     * *  返回一个布尔值判断是否修改成功
     *
     * @param photoImgUrl
     * @param nickName
     * @param sex
     * @param signInfo
     * @param phone
     * @param email
     * @return
     */
    @Override
    public boolean updateInfo(Integer userId, String photoImgUrl, String nickName, String sex, String signInfo, String phone, String email) {
        Connection con = null;
        PreparedStatement ps = null;
        //定义sql语句
        String sql = "update user set photoImgUrl=?,nickName=?,sex=?,signInfo=?,phone=?,email=? WHERE userId=?;";
        con = JdbcUtil.getConnection();
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1, photoImgUrl);
            ps.setString(2, nickName);
            ps.setString(3, sex);
            ps.setString(4, signInfo);
            ps.setString(5, phone);
            ps.setString(6, email);
            int row = ps.executeUpdate();
            return row > 0 ;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * *    通过用户id找到该用户
     *      充值鱼币
     * *    返回一个充值后的金额
     *
     * @param userId
     * @return
     */
    @Override
    public Double rechargeBalance(Integer userId, Double investMoney){
        Connection con = null;
        PreparedStatement ps = null;
        //定义sql语句
        String sql = "update user set balance=balance+? WHERE userId=?";
        con = JdbcUtil.getConnection();
        try {
            ps = con.prepareStatement(sql);
            ps.setDouble(1, investMoney);
            ps.setInt(2, userId);
            int row = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return selectInfoByid(userId).getBalance();
    }


    /**
     * 通过用户id找到该用户的消费记录
     *
     * @param userId
     * @return
     */
    @Override
    public ArrayList<Record> selectRecordByid(Integer userId) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Record> ar=new ArrayList<Record>();
        try {
            //定义sql语句
            String sql = "SELECT * from recordsofconsumption LEFT JOIN gift ON\n" +
                    "recordsofconsumption.rocGift=gift.giftId LEFT JOIN `user` ON\n" +
                    "recordsofconsumption.forAnchor=`user`.userId where  recordsofconsumption.userId=?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setInt(1, userId);
            //执行sql语句
            rs = ps.executeQuery();
            while (rs.next()) {
                Record r= new Record();
                Gift g=new Gift();
                User u = new User();
                r.setRecordId(rs.getInt("rocId"));
                r.setRocTime(rs.getDate("rocTime"));//交易时间
                g.setGiftName(rs.getString("giftName"));//礼物名
                g.setGiftPrice(rs.getDouble("giftPrice"));//礼物单价
                g.setGiftImgUrl(rs.getString("giftImgUrl"));//礼物图片展示路径
                g.setGiftId(rs.getInt("giftId"));
                r.setGift(g);//返回一个礼物对象
                u.setNickName(rs.getString("nickName"));
                r.setUser(u);
                r.setRocNums(rs.getInt("rocNums"));//礼物数量
                ar.add(r);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }  finally {
            JdbcUtil.close(con, ps, rs);
        }
        return ar;
    }

    /**
     * 通过主播id找到该主播的收入记录
     *
     * @param userId
     * @return
     */
    @Override
    public ArrayList<Record> selectRecordByAnchodId(Integer userId) {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        ArrayList<Record> ar=new ArrayList<Record>();
        try {
            //定义sql语句
            String sql = "SELECT * from recordsofconsumption LEFT JOIN gift ON\n" +
                    "recordsofconsumption.rocGift=gift.giftId LEFT JOIN `user` ON\n" +
                    "recordsofconsumption.forAnchor=`user`.userId where  recordsofconsumption.forAnchor=?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setInt(1, userId);
            //执行sql语句
            rs = ps.executeQuery();
            while (rs.next()) {
                Record r= new Record();
                Gift g=new Gift();
                User u = new User();
                r.setRecordId(rs.getInt("rocId"));
                r.setRocTime(rs.getDate("rocTime"));//交易时间
                g.setGiftName(rs.getString("giftName"));//礼物名
                g.setGiftPrice(rs.getDouble("giftPrice"));//礼物单价
                g.setGiftImgUrl(rs.getString("giftImgUrl"));//礼物图片展示路径
                g.setGiftId(rs.getInt("giftId"));
                r.setGift(g);//返回一个礼物对象
                u.setNickName(rs.getString("nickName"));
                r.setUser(u);
                r.setRocNums(rs.getInt("rocNums"));//礼物数量
                ar.add(r);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }  finally {
            JdbcUtil.close(con, ps, rs);
        }
        return ar;
    }

    /**
     * 方法概述：   用户购买礼物时  变更余额
     * @param phone
     * @return
     */
    @Override
    public Double getPrice(String phone) {
        Connection con = null;
        PreparedStatement ps =null;
        ResultSet rs =null;
        Double price=0.0;
        try {
            String sql = "SELECT balance from user where phone = ?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setString(1,phone);
            rs = ps.executeQuery();
            if (rs.next()){
               price = rs.getDouble("balance");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(con,ps,rs);
        }
        return price;
    }

    /**
     * 方法概述：  修改用户余额
     * @param phone
     * @param is
     */
    @Override
    public void upDatePrice(String phone, Double is) {
        Connection con =null;
        PreparedStatement ps = null;

        int a =0;
        try {
            String sql = "update user set balance =? where phone =?";
            con =JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setDouble(1,is);
            ps.setString(2,phone);
            a = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(con,ps,null);
        }
    }

    /***
     * 方法概述：  增加主播余额
     * @param balance 当前余额
     * @param userId 当前主播ID
     */
    @Override
    public void upDateAnchor(Double balance, int userId) {
        Connection con = null;
        PreparedStatement ps = null;

        try {
            String sql = "UPDATE user set balance =? WHERE userId=?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setDouble(1, balance);
            ps.setInt(2,userId);
            ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(con,ps,null);
        }
    }

    /**
     * 用户签到
     * @param userId
     * @return
     */
    @Override
    public boolean signDay(int userId) {
        Connection con = null;
        PreparedStatement ps = null;

        try {
            String sql = "UPDATE user set signDay =signDay+1 WHERE userId=?";
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            ps.setInt(1,userId);
            int row = ps.executeUpdate();
            return row > 0 ;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JdbcUtil.close(con,ps,null);
        }
        return false;
    }


    /**
     * 删除user表中的验证码
     *
     * @param phone
     */
    private boolean deleteVeriCodeFromUser(String phone) {
        Connection con = null;
        PreparedStatement ps = null;
        int rows = 0;
        //定义sql语句
        String sql = "UPDATE user set veriCode = 0,deadline = now() where phone = ?";
        try {
            con = JdbcUtil.getConnection();
            ps = con.prepareStatement(sql);
            //给占位符赋值
            ps.setString(1, phone);
            //执行sql语句
            rows = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(con, ps, null);
        }
        return rows > 0;
    }


}
